package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.annotation.AutoFill;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.enumeration.OperationType;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorsMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorsMapper dishFlavorsMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;

    /**
     * add dish with flavor
     * @param dishDTO
     */
    @Override
    @Transactional//多表保证数据的一致
    @AutoFill(OperationType.INSERT)
    public void addDish(DishDTO dishDTO) {
        Dish dish = new Dish();
//                Dish.builder()
//                .createTime(LocalDateTime.now())
//                .updateTime(LocalDateTime.now())
//                .createUser(BaseContext.getCurrentId())
//                .updateUser(BaseContext.getCurrentId())
//                .build();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.insert(dish);

        //向flavor表插入
        Long dishId = dish.getId();
        List<DishFlavor>flavors =dishDTO.getFlavors();
        if(flavors!=null&& !flavors.isEmpty()){
            //在插入完菜品之后立刻初始化flavor的id
            flavors.forEach(flavor->{
                flavor.setDishId(dishId);
            });

            dishFlavorsMapper.insertBatch(flavors);

        }
    }

    /**
     * page dish
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * delete batch
     * @param ids
     */
    @Override
    public void deleteBatch(List<Long> ids) {
        //状态必须为不卖，且和套餐没联系
        for(Long id : ids){
            if(dishMapper.getStatusById(id) != StatusConstant.DISABLE)
                throw new DeletionNotAllowedException
                        (MessageConstant.DISH_ON_SALE);


            List<Long>setmealIds = setmealDishMapper.getSetmealIdsByDishIds(id);
            if(!setmealIds.isEmpty())
                throw new DeletionNotAllowedException
                        (MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //删除flavor 和 dish
            dishMapper.deleteById(ids);
            dishFlavorsMapper.deleteByDishId(ids);
        }

    /**
     * get dish by id
     *
     * @param id
     * @return
     */
    @Override
    public DishVO getById(Long id) {
        Dish dish = dishMapper.getById(id);
        List<DishFlavor> dishFlavors = dishFlavorsMapper.getById(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(dishFlavors);
        System.out.println(dishVO);
        return dishVO;
    }

    /**
     * get dishs by categoryid
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorsMapper.getById(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }


    /**
     * update dish
     * @param dishDTO
     */
    @Override
    @AutoFill(value = OperationType.UPDATE)
    public void updateDish(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.update(dish);

        //先删除后插入 为了防止覆盖时产生的假覆盖
        dishFlavorsMapper.deleteByDishId(Collections.singletonList(dishDTO.getId()));
        List<DishFlavor>flavors =dishDTO.getFlavors();
        if(flavors!=null && !flavors.isEmpty()){
            flavors.forEach(flavor->{
                flavor.setDishId(dish.getId());
            });
            dishFlavorsMapper.insertBatch(flavors);
        }

    }

}